const { ccclass, property } = cc._decorator;
const gfx = cc['gfx'];

const vertexFmt = new gfx.VertexFormat([
    { name: gfx.ATTR_POSITION, type: gfx.ATTR_TYPE_FLOAT32, num: 2 },
    { name: gfx.ATTR_UV0, type: gfx.ATTR_TYPE_FLOAT32, num: 2 },
    { name: gfx.ATTR_UV1, type: gfx.ATTR_TYPE_FLOAT32, num: 2 },
    { name: "a_p", type: gfx.ATTR_TYPE_FLOAT32, num: 2 },
    { name: "a_q", type: gfx.ATTR_TYPE_FLOAT32, num: 2 },
    // { name: gfx.ATTR_COLOR, type: gfx.ATTR_TYPE_FLOAT32, num: 4, normalize: true },
])
@ccclass
export default class loopSpriteAssembler extends cc.Assembler {

    floatsPerVert = 10;
    vertexesCount = 4;
    indicesCount = 6;

    uvOffset = 2;

    _moveSpeed: cc.Vec2 = cc.v2(0, 0);
    get moveSpeed() {
        return this._moveSpeed;
    }
    set moveSpeed(v: cc.Vec2) {
        this._moveSpeed = v;
    }

    public _renderData: cc.RenderData = null;
    public _local: Array<any> = [];
    public vertexes: Array<cc.Vec2> = [];

    get verticesFloats() {
        return this.floatsPerVert * this.vertexesCount;
    }

    init(comp:cc.Sprite) {
        super.init(comp);
        this._renderData = new cc.RenderData();
        this._renderData.init(this);

        this.initLocal();
        this.initData();
    }

    initLocal() {
        this._local = [];
        this._local.length = this.vertexesCount;
    }
    initData() {
        let data = this._renderData;
        data.createFlexData(0, this.verticesFloats, this.indicesCount, this.getVfmt())

        // createFlexData不会填充顶点索引信息，手动补充一下
        let indices = data.iDatas[0];
        let count = indices.length / this.indicesCount;
        for (let i = 0, idx = 0; i < count; i++) {
            let vertextID = i * 4;
            indices[idx++] = vertextID + 0;
            indices[idx++] = vertextID + 1;
            indices[idx++] = vertextID + 2;
            indices[idx++] = vertextID + 0;
            indices[idx++] = vertextID + 2;
            indices[idx++] = vertextID + 3;
        }
    }
    getVfmt() {
        return vertexFmt;
    }
    // getBuffer() {
    //     //@ts-ignore
    //     return cc.renderer._handle._meshBuffer;
    // }
    getBuffer() {
        //@ts-ignore
        return cc.renderer._handle.getBuffer("mesh", this.getVfmt());
    }

    updateRenderData(sprite) {
        if (sprite._vertsDirty) {
            this.updateVerts(sprite);
            this.updateUVs(sprite);
            this.updateColor(sprite, null);
            sprite._vertsDirty = false;
        }
    }

    // 将准备好的顶点数据填充进 VertexBuffer 和 IndiceBuffer
    fillBuffers(comp, renderer) {
        if (renderer.worldMatDirty) {
            this.updateWorldVerts(comp);
        }

        let renderData = this._renderData;
        let vData = renderData.vDatas[0];
        let iData = renderData.iDatas[0];

        let buffer = this.getBuffer(/*renderer*/);
        let offsetInfo = buffer.request(this.vertexesCount, this.indicesCount);

        // buffer data may be realloc, need get reference after request.

        // fill vertices
        let vertexOffset = offsetInfo.byteOffset >> 2,
            vbuf = buffer._vData;

        if (vData.length + vertexOffset > vbuf.length) {
            vbuf.set(vData.subarray(0, vbuf.length - vertexOffset), vertexOffset);
        } else {
            vbuf.set(vData, vertexOffset);
        }

        // fill indices
        let ibuf = buffer._iData,
            indiceOffset = offsetInfo.indiceOffset,
            vertexId = offsetInfo.vertexOffset;             // vertexId是已经在buffer里的顶点数，也是当前顶点序号的基数
        for (let i = 0, l = iData.length; i < l; i++) {
            ibuf[indiceOffset++] = vertexId + iData[i];
        }
    }


    /**
     * 1 2
     *  0
     * 4 3
     */

    updateUVs(sprite) {
        let uvs = sprite.spriteFrame.uv;
        let l = uvs[0],
            b = uvs[1],
            r = uvs[6],
            t = uvs[7]
            ;

        let uv = [l, t, r, t, r, b, l, b];
        if (sprite.spriteFrame.isRotated()) {
            uv = [r, b, r, t, l, t, l, b];
            this.moveSpeed = cc.v2(-this.moveSpeed.y, -this.moveSpeed.x);
        }
        let uvOffset = this.uvOffset;
        // let uv1Offset = this.uv1Offset;
        let floatsPerVert = this.floatsPerVert;
        let verts = this._renderData.vDatas[0];
        // render data = verts = x|y|u|v|color|x|y|u|v|color|...
        // 填充render data中5个顶点的uv部分
        let sx = this.moveSpeed.x;
        let sy = this.moveSpeed.y;

        let px = 1.0 / (r - l),
            qx = -l * px;
        let py = 1.0 / (b - t),
            qy = -t * py;

        for (let i = 0; i < this.vertexesCount; i++) {
            let srcOffset = i * 2;
            let dstOffset = floatsPerVert * i + uvOffset;
            // let dst1Offset = floatsPerVert * i + uv1Offset;
            verts[dstOffset] = uv[srcOffset];
            verts[dstOffset + 1] = uv[srcOffset + 1];

            verts[dstOffset + 2] = sx;
            verts[dstOffset + 3] = sy;

            verts[dstOffset + 4] = px;
            verts[dstOffset + 5] = py;

            verts[dstOffset + 6] = qx;
            verts[dstOffset + 7] = qy;
        }
        console.log('uv', verts)
    }

    updateColor(comp, color = null) {
        // // render data = verts = x|y|u|v|color|x|y|u|v|color|...
        // // 填充render data中4个顶点的color部分
        // let uintVerts = this._renderData.uintVDatas[0];
        // if (!uintVerts) return;
        // color = color != null ? color : comp.node.color._val;
        // let floatsPerVert = this.floatsPerVert;
        // let colorOffset = this.colorOffset;
        // for (let i = colorOffset, l = uintVerts.length; i < l; i += floatsPerVert) {
        //     uintVerts[i] = color;
        // }
    }
    ctx: cc.Graphics = null;
    updateVerts(sprite: cc.Sprite) {

        let node = sprite.node,
            cw = node.width, ch = node.height,
            appx = node.anchorX * cw, appy = node.anchorY * ch,
            l, b, r, t;


        let local = this._local;
        local[0] = cc.v2(-cw / 2, ch / 2);
        local[1] = cc.v2(cw / 2, ch / 2);
        local[2] = cc.v2(cw / 2, -ch / 2);
        local[3] = cc.v2(-cw / 2, -ch / 2);

        this.updateWorldVerts(sprite);
        // let verts = this._renderData.vDatas[0];
    }

    updateWorldVerts(comp) {
        if (CC_NATIVERENDERER) {
            this.updateWorldVertsNative(comp);
        } else {
            this.updateWorldVertsWebGL(comp);
        }
    }

    updateWorldVertsWebGL(comp) {
        let local = this._local;
        let verts = this._renderData.vDatas[0];

        let matrix = comp.node._worldMatrix;
        let matrixm = matrix.m,
            a = matrixm[0], b = matrixm[1], c = matrixm[4], d = matrixm[5],
            tx = matrixm[12], ty = matrixm[13];
        /*
        m00 = 1, m01 = 0, m02 = 0, m03 = 0,
        m04 = 0, m05 = 1, m06 = 0, m07 = 0,
        m08 = 0, m09 = 0, m10 = 1, m11 = 0,
        m12 = 0, m13 = 0, m14 = 0, m15 = 1
        */
        // [a,b,c,d] = _worldMatrix[1,2,4,5] == [1,0,0,1]
        // _worldMatrix[12,13]是xy的平移量
        // 即世界矩阵的左上角2x2是单元矩阵，说明在2D场景内没有出现旋转或者缩放
        let justTranslate = a === 1 && b === 0 && c === 0 && d === 1;

        // render data = verts = x|y|u|v|color|x|y|u|v|color|...
        // 填充render data中4个顶点的xy部分
        let index = 0;
        let floatsPerVert = this.floatsPerVert;
        // 4对xy分别乘以 [2,2]仿射矩阵，然后+平移量
        // console.log('local', local)
        let posList: Array<cc.Vec2> = [];
        for (let i = 0; i < local.length; i++) {
            let p = local[i];
            // mid
            verts[index] = p.x * a + p.y * c + tx;
            verts[index + 1] = p.x * b + p.y * d + ty;
            posList.push(cc.v2(verts[index], verts[index + 1]))
            index += floatsPerVert;
        }
        console.log('local', local)
        console.log('posList', posList)
        // if (CC_PREVIEW) {
        //     if (!this.ctx) {
        //         let ctxNode = new cc.Node('ctxNode');
        //         ctxNode.parent = cc.director.getScene();
        //         let ctx = ctxNode.addComponent(cc.Graphics);
        //         ctx.lineWidth = 4;
        //         ctx.strokeColor = cc.color(255, 0, 0);
        //         this.ctx = ctx;
        //     }
        //     this.ctx.clear();
        //     for (let i = 0; i < posList.length; i++) {
        //         comp.scheduleOnce(() => {
        //             let p0 = posList[i];
        //             let p1 = i != posList.length - 1 ? posList[i + 1] : posList[0];
        //             this.ctx.moveTo(p0.x, p0.y);
        //             this.ctx.lineTo(p1.x, p1.y);
        //             this.ctx.stroke();
        //         }, i * 0.5)
        //     }
        // }
    }

    // native场景下使用的updateWorldVerts
    // copy from \jsb-adapter-master\engine\assemblers\assembler-2d.js
    updateWorldVertsNative(comp) {
        let local = this._local;
        let verts = this._renderData.vDatas[0];
        let floatsPerVert = this.floatsPerVert;

        let index: number = 0;
        for (let i = 0; i < local.length; i++) {
            let p = local[i];
            // mid
            verts[index] = p.x;
            verts[index + 1] = p.y;
            index += floatsPerVert;
        }
    }

    packToDynamicAtlas(comp, frame) {
        if (CC_TEST) return;

        if (!frame._original && cc.dynamicAtlasManager && frame._texture.packable) {
            let packedFrame = cc.dynamicAtlasManager.insertSpriteFrame(frame);
            //@ts-ignore
            if (packedFrame) {
                frame._setDynamicAtlasFrame(packedFrame);
            }
        }
        let material = comp._materials[0];
        if (!material) return;

        if (material.getProperty('texture') !== frame._texture) {
            // texture was packed to dynamic atlas, should update uvs
            comp._vertsDirty = true;
            comp._activateMaterial();
        }
    }
}
